import React from 'react'
import PropTypes from 'prop-types'
import { Link, Redirect } from 'react-router-dom'
export default class UpdateUserProfile extends React.Component {
    static propTypes = {
        username: PropTypes.string,
        first_name: PropTypes.string,
        last_name: PropTypes.string,
        error: PropTypes.string,
        updateProfile: PropTypes.func.isRequired,
        isUpdate: PropTypes.bool.isRequired,
        isLogin: PropTypes.bool,
    }    
    constructor(props){
        super(props)
        this.state = {
            username: this.props.username,
            first_name: this.props.first_name,
            last_name: this.props.last_name,            
        }
        this.handleChange = this.handleChange.bind(this)
        this.handleSubmit = this.handleSubmit.bind(this)
    }
    handleSubmit(event) {
        this.props.updateProfile(this.state)
        event.preventDefault()
    }
    handleChange(event){
        this.setState({[event.target.name]: event.target.value})
    }
    render() {
        if (!this.props.isLogin) {
            return <Redirect to="/login" />
        }
        if(this.props.isUpdate){
            return <Redirect to="/user"/>
        }
        return (
        <div>
        <form onSubmit = {this.handleSubmit} className = "form">
            <div>
                <div>{this.props.error}</div>
            <label htmlFor="user-name">username</label>
            <input id="user-name" value={this.state.username} onChange={this.handleChange} name="username"/>
            </div>
            <div>
            <label htmlFor="user-first-name">First Name</label>
            <input id="user-first-name" value={this.state.first_name} onChange={this.handleChange} name="first_name"/>
            </div>
            <div>
            <label htmlFor="user-last-name">Last Name</label>
            <input id="user-last-name" value={this.state.last_name} onChange={this.handleChange} name="last_name"/>
            </div>
            <input type="submit" value="Update"/>            
        </form>
        <Link to="/user">Cancel</Link>
        </div>
        )
    }
}